/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo17.config;

import cn.edu.zua.demo17.service.TestUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/29 16:48
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private TestUserServiceImpl userService;

    @Autowired
    public void setUserService(TestUserServiceImpl userService) {
        this.userService = userService;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated()//所有请求必须登陆后访问
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .permitAll()//登录界面，错误界面可以直接访问
            .and()
            .logout()
            .permitAll();//注销请求可直接访问
    }

    /**
     * 用户信息配置
     * @param auth 用户信息管理器
     * @throws Exception 异常信息
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//修改以前
//        auth
//                .inMemoryAuthentication()
//                .withUser("root")
//                .password("root")
//                .roles("user")
//                .and()
//                .passwordEncoder(CharEncoder.getINSTANCE());

//修改以后
        auth
                .userDetailsService(userService)
                .passwordEncoder(passwordEncoder());

    }

    /**
     * 密码加密
     * @return 返回加密后的密码
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

